package com.twang.stock.utils.clawer;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.core.io.ClassPathResource;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HttpHelper {
    private static  String COOKIE = "_gat=1; nsfw-click-load=off; gif-click-load=on;_ga=GA1.2.1861846600.1423061484";

    private static String getCOOKIE() throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        // String jsFileName = GaiNianZiJingPaiHangTask.class.getClassLoader().getResource("static/js/aes.min.js").getFile(); // 读取js文件
        // FileReader reader = new FileReader(); // 执行指定脚本
        //spring boot 不能直接这样读取路径，jar包中会报错
        ClassPathResource classPathResource = new ClassPathResource("static/js/aes.min.js");
        InputStreamReader  reader=   new InputStreamReader(classPathResource.getInputStream());
        engine.eval(reader);
        if (engine instanceof Invocable) {
            Invocable invoke = (Invocable) engine; // 调用merge方法，并传入两个参数
            // c = merge(2, 3);
            String c = (String) invoke.invokeFunction("v");
            COOKIE = "v=" + c;
        }
        reader.close();
        return COOKIE;
    }

    public static String getHtmlStrByUrl(String url, CloseableHttpClient httpClient, String COOKIE, String USER_AGENT) {
        HttpGet httpGetForFName = new HttpGet(url);
        httpGetForFName.addHeader("User-Agent", USER_AGENT);
       httpGetForFName.addHeader("Cookie", COOKIE);
       httpGetForFName.addHeader("Content-Type", "text/html; charset=gbk");

        // 发送请求，并执行
        CloseableHttpResponse response;
        String html = "";
        try {
            response = httpClient.execute(httpGetForFName);
            InputStream in = response.getEntity().getContent();
            html = convertStreamToString(in,"utf-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return html;
    }

    public static String convertStreamToString(InputStream in,String charSet) {
        StringBuilder sb = new StringBuilder();
        try {

            InputStreamReader isr = new InputStreamReader(in, charSet);
            BufferedReader reader = new BufferedReader(isr);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();

    }

    public static String getHtmlStrByUrl(String url, CloseableHttpClient httpClient, String USER_AGENT) throws Exception {
        HttpGet httpGetForFName = new HttpGet(url);
        httpGetForFName.addHeader("User-Agent", USER_AGENT);
        httpGetForFName.addHeader("Cookie", getCOOKIE());
        httpGetForFName.addHeader("Content-Type", "text/html; charset=gbk");
        httpGetForFName.addHeader("Accept-Encoding", "gzip, deflate");
        httpGetForFName.addHeader("Connection", "keep-alive");
        // 发送请求，并执行
        CloseableHttpResponse response;
        String html = "";
        try {
            response = httpClient.execute(httpGetForFName);
            // response植入cookie
            Header[] ssoResponseHeader = response.getHeaders("Set-Cookie");
            InputStream in = response.getEntity().getContent();
            html = convertStreamToString(in,"gbk");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return html;
    }
}
